package com.yxr.aspect;


import com.alibaba.fastjson.JSON;
import com.yxr.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("@annotation( com.yxr.annotation.SystemLog)")
    public void pt(){}

    @Around("pt()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Object proceed = null; //目标方法返回值
        try {
            handleBefore(joinPoint);
            proceed = joinPoint.proceed();
            handlerAfter(proceed);
        } finally {
            // 结束后换行
            log.info("=======================end=======================" + System.lineSeparator());
        }

        return proceed;
    }

    private void handleBefore(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取增强方法上注解对象
        SystemLog systemLog = getSystemLog(joinPoint);

        log.info("======================Start======================");
// 打印请求 URL
        log.info("请求URL   : {}",request.getRequestURI());
// 打印描述信息
        log.info("接口描述   : {}",systemLog.businessName() );
// 打印 Http method
        log.info("请求方式   : {}",request.getMethod() );
// 打印调用 controller 的全路径以及执行方法
        log.info("请求类名   : {}.{}",joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature)joinPoint.getSignature()).getName() );
// 打印请求的 IP
        log.info("访问IP    : {}",request.getRemoteHost());
// 打印请求入参
        log.info("传入参数   : {}", JSON.toJSON(joinPoint.getArgs()));

    }

    private SystemLog getSystemLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLog annotation = signature.getMethod().getAnnotation(SystemLog.class);
        return annotation;
    }

    private void handlerAfter(Object proceed) {
        // 打印出参
        log.info("返回参数   : {}",JSON.toJSON(proceed) );
    }
}
